package dfl.bysj.service.impl;

import dfl.bysj.config.RedisKey;
import dfl.bysj.entity.Honest;
import dfl.bysj.mapper.HonestMapper;
import dfl.bysj.service.HonestService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author DFL
 * @since 2022-04-26
 */
@Service
public class HonestServiceImpl extends ServiceImpl<HonestMapper, Honest> implements HonestService {
    private RedisTemplate redisTemplate;

    private List<Honest> honests;


    private AtomicReference<Honest> honestAtomicReference= new AtomicReference<>(new Honest());


    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private void getHonests(){
        honests= (List<Honest>) redisTemplate.opsForValue().get(RedisKey.ALL_HONEST);
        if (honests==null){
            updateRedisOfHoensts();
        }
    }

    private void updateRedisOfHoensts(){
        honests=list();
        redisTemplate.opsForValue().set(RedisKey.ALL_HONEST,honests,7, TimeUnit.DAYS);
    }

    @Override
    public Float getGradeByHonId(int i) {
        getHonests();
        honests.stream()
                .filter(s->s.getHonId().equals(i))
                .forEach(s->honestAtomicReference.set(s));
        return honestAtomicReference.get().getGrade();
    }
}
